package com.gxuwz.nio;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

/**
 * bufeer的基本使用步骤
 * 1写入数据到 Buffer
 * （2）调用 flip()方法
 * （3）从 Buffer 中读取数据
 * （4）调用 clear()方法或者 compact()方法
 */
public class DatagramChannelDemo {

    /**
     * 发包
     * @throws IOException
     * @throws InterruptedException
     */
    @Test
    public  void sendDa() throws IOException, InterruptedException {
        DatagramChannel server=DatagramChannel.open();
        InetSocketAddress sendAddress= new InetSocketAddress("127.0.0.1", 9999);

        server.configureBlocking(false);

        //发送数据
        while (true) {
            server.send(ByteBuffer.wrap("发包".getBytes("UTF-8")), sendAddress);
            System.out.println("发包端发包");
            Thread.sleep(1000);
        }

    }

    /**
     * 收包
     */
    @Test
    public void receive() throws IOException {
        DatagramChannel receiveChannel = DatagramChannel.open();
        InetSocketAddress address = new InetSocketAddress(9999);

        receiveChannel.bind(address);
        ByteBuffer receivebuffer = ByteBuffer.allocate(512);

        while (true){
            receivebuffer.clear();
            SocketAddress receive = receiveChannel.receive(receivebuffer);
            receivebuffer.flip();
            System.out.println(receive.toString()+"");
            System.out.println(Charset.forName("UTF-8").decode(receivebuffer));
        }


    }
}
